﻿using FCDB.Entity.EntityEx;
using FCDB.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FCDB.Repository
{
    public class WfActivityInstanceTasksRepository : LogicBase, ILogic
    {

        //       SELECT     dbo.WfTasks.ID AS TaskID, dbo.WfActivityInstance.AppName, dbo.WfActivityInstance.AppInstanceID, dbo.WfActivityInstance.ProcessGUID, 
        //                      dbo.WfTasks.ProcessInstanceID, dbo.WfActivityInstance.ActivityGUID, dbo.WfActivityInstance.ID AS ActivityInstanceID, dbo.WfActivityInstance.ActivityName, 
        //                      dbo.WfActivityInstance.ActivityType, dbo.WfTasks.TaskType, dbo.WfTasks.AssignedToUserName, dbo.WfTasks.CreatedDateTime, dbo.WfTasks.EndedDateTime, 
        //                      dbo.WfTasks.EndedByUserID, dbo.WfTasks.EndedByUserName, dbo.WfTasks.TaskState, dbo.WfActivityInstance.State AS ActivityState, 
        //                      dbo.WfActivityInstance.IsActivityCompleted, dbo.WfTasks.RecordStatusInvalid, dbo.WfProcessInstance.ProcessState, dbo.WfTasks.CreatedByUserID, 
        //                      dbo.WfTasks.CreatedByUserName
        //FROM         dbo.WfActivityInstance INNER JOIN
        //                      dbo.WfTasks ON dbo.WfActivityInstance.ID = dbo.WfTasks.ActivityInstanceID INNER JOIN
        //                      dbo.WfProcessInstance ON dbo.WfActivityInstance.ProcessInstanceID = dbo.WfProcessInstance.ID AND dbo.WfTasks.ProcessInstanceID = dbo.WfProcessInstance.ID
        private RegularMeetingRepository Regularrespository = new RegularMeetingRepository();
        public static IQueryable<WfActivityInstanceTasksEx> GetActivityInstanceTasks()
        {
            var query = from item in DBHelper.WfActivityInstance
                        join task in DBHelper.WfTasks on item.ID equals task.ActivityInstanceID
                        join processInstance in DBHelper.WfProcessInstance on item.ProcessInstanceID equals processInstance.ID
                        select new WfActivityInstanceTasksEx()
                        {
                            ActivityGUID = item.ActivityGUID,
                            ActivityInstanceID = task.ActivityInstanceID,
                            ActivityName = task.ActivityName,
                            ActivityState = item.State,
                            ActivityType = item.ActivityType,
                            AppInstanceID = item.AppInstanceID,
                            AppName = item.AppName,
                            AssignedToUserID = task.AssignedToUserID,
                            AssignedToUserName = task.AssignedToUserName,
                            CreatedByUserID = task.CreatedByUserID,
                            CreatedByUserName = task.CreatedByUserName,
                            CreatedDateTime = task.CreatedDateTime,
                            EndedByUserID = task.EndedByUserID,
                            EndedByUserName = task.EndedByUserName,
                            EndedDateTime = task.EndedDateTime,
                            IsActivityCompleted = item.IsActivityCompleted,
                            ProcessGUID = item.ProcessGUID,
                            ProcessInstanceID = item.ProcessInstanceID,
                            ProcessState = processInstance.ProcessState,
                            TaskID = task.ID,
                            TaskState = task.TaskState,
                            TaskType = task.TaskType,
                            RecordStatusInvalid = task.RecordStatusInvalid,
                            ReadyTaskType = 1,
                            SendUserID = Guid.NewGuid(),

                            // 测试为了判断是否是撤回而建立
                            State = item.State
                        };
            return query;
        }


        public static IQueryable<WfActivityInstanceTasksEx> GetComprehensiveTasks()
        {
            var query = from item in DBHelper.WfActivityInstance
                        join task in DBHelper.WfTasks on item.ID equals task.ActivityInstanceID
                        join processInstance in DBHelper.WfProcessInstance on item.ProcessInstanceID equals processInstance.ID
                        select new WfActivityInstanceTasksEx()
                        {
                            ActivityGUID = item.ActivityGUID,
                            ActivityInstanceID = task.ActivityInstanceID,
                            ActivityName = task.ActivityName,
                            ActivityState = item.State,
                            ActivityType = item.ActivityType,
                            AppInstanceID = item.AppInstanceID,
                            AppName = item.AppName,
                            AssignedToUserID = task.AssignedToUserID,
                            AssignedToUserName = task.AssignedToUserName,
                            CreatedByUserID = task.CreatedByUserID,
                            CreatedByUserName = task.CreatedByUserName,
                            CreatedDateTime = task.CreatedDateTime,
                            EndedByUserID = task.EndedByUserID,
                            EndedByUserName = task.EndedByUserName,
                            EndedDateTime = task.EndedDateTime,
                            IsActivityCompleted = item.IsActivityCompleted,
                            ProcessGUID = item.ProcessGUID,
                            ProcessInstanceID = item.ProcessInstanceID,
                            ProcessState = processInstance.ProcessState,
                            TaskID = task.ID,
                            TaskState = task.TaskState,
                            TaskType = task.TaskType,
                            RecordStatusInvalid = task.RecordStatusInvalid,
                            ReadyTaskType = 1,
                            SendUserID = Guid.NewGuid(),

                            // 测试为了判断是否是撤回而建立
                            State = item.State
                        };
            return query;
        }


        public IList<WfActivityInstanceTasksEx> GetTaskOfMine(long appInstanceID, Guid processGUID, Guid userID)
        {
            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.AppInstanceID == appInstanceID && item.ProcessGUID == processGUID && item.AssignedToUserID == userID
                             && item.ProcessState == 2 && item.ActivityType == 4 && (item.ActivityState == 1 || item.ActivityState == 2)
                        orderby item.TaskID descending
                        select item;
            return query.ToList();
        }
        /// <summary>
        /// 获取当前节点是否为指定审核人或者创建人
        /// </summary>
        /// <param name="appInstanceID"></param>
        /// <param name="processGUID"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public IList<WfActivityInstanceTasksEx> GetTaskOfMineForProcessSendBack(long appInstanceID, Guid processGUID, Guid userID)
        {
            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.AppInstanceID == appInstanceID && item.ProcessGUID == processGUID && (item.AssignedToUserID == userID || item.CreatedByUserID == userID)
                             && item.ProcessState == 2 && item.ActivityType == 4 && (item.ActivityState == 1 || item.ActivityState == 2)
                        orderby item.TaskID descending
                        select item;
            return query.ToList();
        }
        public WfActivityInstanceTasksEx GetReadyTaskOfMine(long appInstanceID, Guid processGUID, Guid userID)
        {
            //processState:2 -running 流程处于运行状态
            //activityType:4 -表示“任务”类型的节点
            //activityState: 1-ready（准备）
            //            string whereSql = @"WHERE AppInstanceID=@appInstanceID AND ProcessGUID=@processGUID AND AssignedToUserID=@userID 
            //                                AND ProcessState=2 AND ActivityType=4 AND ActivityState=1
            //                           ORDER BY TASKID DESC";
            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.AppInstanceID == appInstanceID && item.ProcessGUID == processGUID && item.AssignedToUserID == userID
                    && item.ProcessState == 2 && item.ActivityType == 4 && item.ActivityState == 1
                        orderby item.TaskID descending
                        select item;


            //取出唯一待办任务记录，并返回。
            WfActivityInstanceTasksEx task = query.FirstOrDefault();
            return task;
        }

        public IList<WfActivityInstanceTasksEx> GetTasksPaged(long appInstanceID, Guid processGUID, Guid userID, int activityState,
            int PageIndex, int PageSize, out int allRowsCount)
        {
            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.AppInstanceID == appInstanceID && item.ProcessState == 2 && item.ActivityType == 4
                        && item.ActivityState == activityState && item.AssignedToUserID == userID
                        && item.ProcessGUID == processGUID
                        orderby item.TaskID descending
                        select item;
            allRowsCount = query.Count();
            if (allRowsCount == 0) return null;
            IList<WfActivityInstanceTasksEx> list = query.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            return list;
        }
        public IList<WfActivityInstanceTasksEx> GetTasksByCreateUserPaged(long appInstanceID, Guid processGUID, Guid userID, int activityState,
            int PageIndex, int PageSize, out int allRowsCount)
        {
            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.AppInstanceID == appInstanceID && item.ProcessState == 2 && item.ActivityType == 4
                        && (item.ActivityState == 1 || item.ActivityState == 2) && item.CreatedByUserID == userID
                        && item.ProcessGUID == processGUID
                        orderby item.TaskID descending
                        select item;
            allRowsCount = query.Count();
            if (allRowsCount == 0) return null;
            IList<WfActivityInstanceTasksEx> list = query.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            return list;
        }

        public IList<WfActivityInstanceTasksEx> GetReadyTaskOfApp(long appInstanceID, Guid processGUID)
        {
            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.AppInstanceID == appInstanceID && item.ProcessGUID == processGUID
                        select item;
            return query.ToList();
        }

        public IList<WfActivityInstanceTasksEx> GetProcessTasks(int appInstanceID, int processInstanceID)
        {
            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.ProcessInstanceID == processInstanceID && item.AppInstanceID == appInstanceID
                        select item;
            return query.ToList();
        }

        public IList<WfActivityInstanceTasksEx> GetProcessTasksWithState(int appInstanceID, int processInstanceID, short state)
        {
            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.ProcessInstanceID == processInstanceID && item.AppInstanceID == appInstanceID && item.TaskState == state
                        select item;
            return query.ToList();
        }

        #region 林坚丁扩展
        /// <summary>
        /// 获取用户的代办流程
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public IList< WfActivityInstanceTasksEx> GetTaskOfMine(Guid userID, int skip, int take, string dtStart, string dtEnd,
            string kewyword, string UserIDs, string DeparmentID, String ProcessGuid,
            out int totalRecord)
        {
            var efemployeeInfoProvider = FB.Providers.AspNetEmployeeInfoProviderManager.Default as FB.Providers.EFEmployeeInfoProvider;
            FB.Providers.EmployeeInfo.EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            var queryTasks = GetActivityInstanceTasks();

            var query = from item in queryTasks
                        where item.AssignedToUserID == userID && item.ProcessState == 2
                        && (item.TaskState == 1 || item.TaskState == 2)
                        && item.ActivityType == 4 && (item.ActivityState == 1 || item.ActivityState == 2)
                        select item;
            var query1 = from item in queryTasks
                         group item by item.AppInstanceID into gitem
                         select new { gitem.Key, TaskID = gitem.Max(mm => mm.TaskID) };
            queryTasks = from item in queryTasks
                         from kk in query1
                         where item.AppInstanceID == kk.Key && item.TaskID == kk.TaskID
                         select item;

            var logQuery = from item in queryTasks
                           from log in DBHelper.FormCirculatedDocumentLog
                           where item.AppInstanceID == log.AppInstanceID && log.Status == 0 && log.UserID == userID
                           select new WfActivityInstanceTasksEx()
                           {
                               ActivityGUID = item.ActivityGUID,
                               ActivityInstanceID = item.ActivityInstanceID,
                               ActivityName = item.ActivityName,
                               ActivityState = item.ActivityState,
                               ActivityType = item.ActivityType,
                               AppInstanceID = item.AppInstanceID,
                               AppName = item.AppName,
                               AssignedToUserID = item.AssignedToUserID,
                               AssignedToUserName = item.AssignedToUserName,
                               CreatedByUserID = item.CreatedByUserID,
                               CreatedByUserName = item.CreatedByUserName,
                               CreatedDateTime = item.CreatedDateTime,
                               EndedByUserID = item.EndedByUserID,
                               EndedByUserName = item.EndedByUserName,
                               EndedDateTime = item.EndedDateTime,
                               IsActivityCompleted = item.IsActivityCompleted,
                               ProcessGUID = item.ProcessGUID,
                               ProcessInstanceID = item.ProcessInstanceID,
                               ProcessState = item.ProcessState,
                               TaskID = item.TaskID,
                               TaskState = item.TaskState,
                               TaskType = item.TaskType,
                               RecordStatusInvalid = item.RecordStatusInvalid,
                               ReadyTaskType = log.CheckType == 1 ? 2 : 3,
                               SendUserID = log.CreateUserID,
                               State = item.State
                           };
            query = query.Concat(logQuery);
            if (!string.IsNullOrEmpty(dtStart) && !string.IsNullOrEmpty(dtEnd))
            {
                DateTime dtStartTime = DateTime.Parse(dtStart);
                DateTime dtEndTime = DateTime.Parse(dtEnd);
                query = query.Where(t => t.CreatedDateTime >= dtStartTime && t.CreatedDateTime <= dtEndTime);
            }
            if (!string.IsNullOrEmpty(kewyword))
            {
                long appInstanceId = 0;
                long.TryParse(kewyword, out appInstanceId);
                if (appInstanceId > 0)
                {
                    query = query.Where(t => t.AppInstanceID == appInstanceId);
                }
                else
                {
                    query = query.Where(t => t.AppName.IndexOf(kewyword) > -1);
                }
            }
            if (!string.IsNullOrEmpty(ProcessGuid))
            {
                query = query.Where(t => t.ProcessGUID == new Guid(ProcessGuid));
            }
            if (!string.IsNullOrEmpty(DeparmentID))
            {
                IList<vw_Employees> employee = Regularrespository.GetEmployeeByDeparment(DeparmentID);
                foreach (var i in employee)
                {
                    UserIDs = UserIDs + ";" + i.UserID.ToString();
                }
            }
            if (!string.IsNullOrEmpty(UserIDs))
            {
                List<Guid?> UserIDList = new List<Guid?>();
                string[] strUserID = UserIDs.Split(";".ToArray());
                foreach (string item in strUserID)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        UserIDList.Add(new Guid(item));
                    }
                }
                query = query.Where(t => UserIDList.Contains(t.CreatedByUserID));
            }

            totalRecord = query.Count();
            IList<WfActivityInstanceTasksEx> list = query.OrderByDescending(t => t.CreatedDateTime).Skip(skip).Take(take).ToList();
            return list;
        }
        /// <summary>
        /// 获取用户的代办流程
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public int GetTaskCountOfMine(Guid userID)
        {

            var queryTasks = GetActivityInstanceTasks();
            var query = from item in queryTasks
                        where item.AssignedToUserID == userID && item.ProcessState == 2
                        && (item.TaskState == 1 || item.TaskState == 2)
                        && item.ActivityType == 4 && (item.ActivityState == 1 || item.ActivityState == 2)
                        select item;
            var query1 = from item in queryTasks
                         group item by item.AppInstanceID into gitem
                         select new { gitem.Key, TaskID = gitem.Max(mm => mm.TaskID) };
            queryTasks = from item in queryTasks
                         from kk in query1
                         where item.AppInstanceID == kk.Key && item.TaskID == kk.TaskID
                         select item;
            var logQuery = from item in queryTasks
                           from log in DBHelper.FormCirculatedDocumentLog
                           where item.AppInstanceID == log.AppInstanceID && log.Status == 0 && log.UserID == userID
                           select new WfActivityInstanceTasksEx()
                           {
                               ActivityGUID = item.ActivityGUID,
                               ActivityInstanceID = item.ActivityInstanceID,
                               ActivityName = item.ActivityName,
                               ActivityState = item.ActivityState,
                               ActivityType = item.ActivityType,
                               AppInstanceID = item.AppInstanceID,
                               AppName = item.AppName,
                               AssignedToUserID = item.AssignedToUserID,
                               AssignedToUserName = item.AssignedToUserName,
                               CreatedByUserID = item.CreatedByUserID,
                               CreatedByUserName = item.CreatedByUserName,
                               CreatedDateTime = item.CreatedDateTime,
                               EndedByUserID = item.EndedByUserID,
                               EndedByUserName = item.EndedByUserName,
                               EndedDateTime = item.EndedDateTime,
                               IsActivityCompleted = item.IsActivityCompleted,
                               ProcessGUID = item.ProcessGUID,
                               ProcessInstanceID = item.ProcessInstanceID,
                               ProcessState = item.ProcessState,
                               TaskID = item.TaskID,
                               TaskState = item.TaskState,
                               TaskType = item.TaskType,
                               RecordStatusInvalid = item.RecordStatusInvalid,
                               ReadyTaskType = 2,
                               SendUserID = log.CreateUserID,
                               State = item.State
                           }; ;
            query = query.Concat(logQuery);
            return query.Count();

        }


        /// <summary>
        /// 获取用户 当前的代办流程
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public WfActivityInstanceTasksEx GetTaskByID(Guid ID)
        {

            var queryTasks = GetActivityInstanceTasks();

            var query = from item in queryTasks
                        where item.ProcessGUID == ID
                        && item.ActivityType == 4 && (item.ActivityState == 1 || item.ActivityState == 2)
                        select item;
            var query1 = from item in queryTasks
                         group item by item.AppInstanceID into gitem
                         select new { gitem.Key, TaskID = gitem.Max(mm => mm.TaskID) };
            queryTasks = from item in queryTasks
                         from kk in query1
                         where item.AppInstanceID == kk.Key && item.TaskID == kk.TaskID
                         select item;

            var logQuery = from item in queryTasks
                           from log in DBHelper.FormCirculatedDocumentLog
                           where item.AppInstanceID == log.AppInstanceID && log.Status == 0 && log.ProcessGUID == ID
                           select new WfActivityInstanceTasksEx()
                           {
                               ActivityGUID = item.ActivityGUID,
                               ActivityInstanceID = item.ActivityInstanceID,
                               ActivityName = item.ActivityName,
                               ActivityState = item.ActivityState,
                               ActivityType = item.ActivityType,
                               AppInstanceID = item.AppInstanceID,
                               AppName = item.AppName,
                               AssignedToUserID = item.AssignedToUserID,
                               AssignedToUserName = item.AssignedToUserName,
                               CreatedByUserID = item.CreatedByUserID,
                               CreatedByUserName = item.CreatedByUserName,
                               CreatedDateTime = item.CreatedDateTime,
                               EndedByUserID = item.EndedByUserID,
                               EndedByUserName = item.EndedByUserName,
                               EndedDateTime = item.EndedDateTime,
                               IsActivityCompleted = item.IsActivityCompleted,
                               ProcessGUID = item.ProcessGUID,
                               ProcessInstanceID = item.ProcessInstanceID,
                               ProcessState = item.ProcessState,
                               TaskID = item.TaskID,
                               TaskState = item.TaskState,
                               TaskType = item.TaskType,
                               RecordStatusInvalid = item.RecordStatusInvalid,
                               ReadyTaskType = 2,
                               SendUserID = log.CreateUserID,



                           }; ;
            query = query.Concat(logQuery);
            IList<WfActivityInstanceTasksEx> list = query.ToList();
            WfActivityInstanceTasksEx returnList = new WfActivityInstanceTasksEx();
            foreach (var i in list)
            {
                returnList = i;
            }
            return returnList;
        }

        // 获取财务可以修改的流程
        public IList<WfActivityInstanceTasksEx> GetTaskOfFinance(int skip, int take, string dtStart, string dtEnd,
           string kewyword, string UserIDs, string DeparmentID, String ProcessGuid,
           out int totalRecord)
        {
            var efemployeeInfoProvider = FB.Providers.AspNetEmployeeInfoProviderManager.Default as FB.Providers.EFEmployeeInfoProvider;
            FB.Providers.EmployeeInfo.EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            var queryTasks = GetActivityInstanceTasks();

            var query = from item in queryTasks
                        where item.ProcessState == 2 
                        && (item.TaskState == 1 || item.TaskState == 2)
                        && item.ActivityType == 4 && (item.ActivityState == 1 || item.ActivityState == 2) && item.ProcessGUID == new Guid("0e37f0c1-737b-4653-93dd-d01a3fbc28f7")
                        select item;
            var query1 = from item in queryTasks
                         group item by item.AppInstanceID into gitem
                         select new { gitem.Key, TaskID = gitem.Max(mm => mm.TaskID) };
            queryTasks = from item in queryTasks
                         from kk in query1
                         where item.AppInstanceID == kk.Key && item.TaskID == kk.TaskID
                         select item;

            var logQuery = from item in queryTasks
                           from log in DBHelper.FormCirculatedDocumentLog
                           where item.AppInstanceID == log.AppInstanceID && log.Status == 0
                           select new WfActivityInstanceTasksEx()
                           {
                               ActivityGUID = item.ActivityGUID,
                               ActivityInstanceID = item.ActivityInstanceID,
                               ActivityName = item.ActivityName,
                               ActivityState = item.ActivityState,
                               ActivityType = item.ActivityType,
                               AppInstanceID = item.AppInstanceID,
                               AppName = item.AppName,
                               AssignedToUserID = item.AssignedToUserID,
                               AssignedToUserName = item.AssignedToUserName,
                               CreatedByUserID = item.CreatedByUserID,
                               CreatedByUserName = item.CreatedByUserName,
                               CreatedDateTime = item.CreatedDateTime,
                               EndedByUserID = item.EndedByUserID,
                               EndedByUserName = item.EndedByUserName,
                               EndedDateTime = item.EndedDateTime,
                               IsActivityCompleted = item.IsActivityCompleted,
                               ProcessGUID = item.ProcessGUID,
                               ProcessInstanceID = item.ProcessInstanceID,
                               ProcessState = item.ProcessState,
                               TaskID = item.TaskID,
                               TaskState = item.TaskState,
                               TaskType = item.TaskType,
                               RecordStatusInvalid = item.RecordStatusInvalid,
                               ReadyTaskType = log.CheckType == 1 ? 2 : 3,
                               SendUserID = log.CreateUserID,
                               State = item.State
                           };
            query = query.Concat(logQuery);
            if (!string.IsNullOrEmpty(dtStart) && !string.IsNullOrEmpty(dtEnd))
            {
                DateTime dtStartTime = DateTime.Parse(dtStart);
                DateTime dtEndTime = DateTime.Parse(dtEnd);
                query = query.Where(t => t.CreatedDateTime >= dtStartTime && t.CreatedDateTime <= dtEndTime);
            }
            if (!string.IsNullOrEmpty(kewyword))
            {
                long appInstanceId = 0;
                long.TryParse(kewyword, out appInstanceId);
                if (appInstanceId > 0)
                {
                    query = query.Where(t => t.AppInstanceID == appInstanceId);
                }
                else
                {
                    query = query.Where(t => t.AppName.IndexOf(kewyword) > -1);
                }
            }
            if (!string.IsNullOrEmpty(ProcessGuid))
            {
                query = query.Where(t => t.ProcessGUID == new Guid(ProcessGuid));
            }
            if (!string.IsNullOrEmpty(DeparmentID))
            {
                IList<vw_Employees> employee = Regularrespository.GetEmployeeByDeparment(DeparmentID);
                foreach (var i in employee)
                {
                    UserIDs = UserIDs + ";" + i.UserID.ToString();
                }
            }
            if (!string.IsNullOrEmpty(UserIDs))
            {
                List<Guid?> UserIDList = new List<Guid?>();
                string[] strUserID = UserIDs.Split(";".ToArray());
                foreach (string item in strUserID)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        UserIDList.Add(new Guid(item));
                    }
                }
                query = query.Where(t => UserIDList.Contains(t.CreatedByUserID));
            }

            totalRecord = query.Count();
            IList<WfActivityInstanceTasksEx> list = query.OrderByDescending(t => t.CreatedDateTime).Skip(skip).Take(take).ToList();
            return list;
        }


        // 获取综合室可以修改的流程
        public IList<WfActivityInstanceTasksEx> GetTaskOfComprehensive(int skip, int take, string dtStart, string dtEnd,
           string kewyword, string UserIDs, string DeparmentID, String ProcessGuid,
           out int totalRecord)
        {
            var efemployeeInfoProvider = FB.Providers.AspNetEmployeeInfoProviderManager.Default as FB.Providers.EFEmployeeInfoProvider;
            FB.Providers.EmployeeInfo.EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            var queryTasks = GetComprehensiveTasks();

            var query = from item in queryTasks
                        join form in DBHelper.FormCDB on item.AppInstanceID equals form.AppInstanceID
                        where 
                        item.ProcessGUID == new Guid("0e37f0c1-737b-4653-93dd-d01a3fbc28f7") &&
                        ((
                        (item.TaskState == 1 || item.TaskState == 2)
                         && (item.ActivityState == 1 || item.ActivityState == 2)
                        ) || item.TaskState == 4 && item.ActivityName.Contains("拟稿人"))
                        select item;

            var query1 = from item in queryTasks
                         group item by item.AppInstanceID into gitem
                         select new { gitem.Key, TaskID = gitem.Max(mm => mm.TaskID) };
            queryTasks = from item in queryTasks
                         from kk in query1
                         where item.AppInstanceID == kk.Key && item.TaskID == kk.TaskID
                         select item;

            var logQuery = from item in queryTasks
                           from log in DBHelper.FormCirculatedDocumentLog
                           where item.AppInstanceID == log.AppInstanceID && log.Status == 0
                           select new WfActivityInstanceTasksEx()
                           {
                               ActivityGUID = item.ActivityGUID,
                               ActivityInstanceID = item.ActivityInstanceID,
                               ActivityName = item.ActivityName,
                               ActivityState = item.ActivityState,
                               ActivityType = item.ActivityType,
                               AppInstanceID = item.AppInstanceID,
                               AppName = item.AppName,
                               AssignedToUserID = item.AssignedToUserID,
                               AssignedToUserName = item.AssignedToUserName,
                               CreatedByUserID = item.CreatedByUserID,
                               CreatedByUserName = item.CreatedByUserName,
                               CreatedDateTime = item.CreatedDateTime,
                               EndedByUserID = item.EndedByUserID,
                               EndedByUserName = item.EndedByUserName,
                               EndedDateTime = item.EndedDateTime,
                               IsActivityCompleted = item.IsActivityCompleted,
                               ProcessGUID = item.ProcessGUID,
                               ProcessInstanceID = item.ProcessInstanceID,
                               ProcessState = item.ProcessState,
                               TaskID = item.TaskID,
                               TaskState = item.TaskState,
                               TaskType = item.TaskType,
                               RecordStatusInvalid = item.RecordStatusInvalid,
                               ReadyTaskType = log.CheckType == 1 ? 2 : 3,
                               SendUserID = log.CreateUserID,
                               State = item.State
                           };
            query = query.Concat(logQuery);
            if (!string.IsNullOrEmpty(dtStart) && !string.IsNullOrEmpty(dtEnd))
            {
                DateTime dtStartTime = DateTime.Parse(dtStart);
                DateTime dtEndTime = DateTime.Parse(dtEnd);
                query = query.Where(t => t.CreatedDateTime >= dtStartTime && t.CreatedDateTime <= dtEndTime);
            }
            if (!string.IsNullOrEmpty(kewyword))
            {
                long appInstanceId = 0;
                long.TryParse(kewyword, out appInstanceId);
                if (appInstanceId > 0)
                {
                    query = query.Where(t => t.AppInstanceID == appInstanceId);
                }
                else
                {
                    query = query.Where(t => t.AppName.IndexOf(kewyword) > -1);
                }
            }
            if (!string.IsNullOrEmpty(ProcessGuid))
            {
                query = query.Where(t => t.ProcessGUID == new Guid(ProcessGuid));
            }
            if (!string.IsNullOrEmpty(DeparmentID))
            {
                IList<vw_Employees> employee = Regularrespository.GetEmployeeByDeparment(DeparmentID);
                foreach (var i in employee)
                {
                    UserIDs = UserIDs + ";" + i.UserID.ToString();
                }
            }
            if (!string.IsNullOrEmpty(UserIDs))
            {
                List<Guid?> UserIDList = new List<Guid?>();
                string[] strUserID = UserIDs.Split(";".ToArray());
                foreach (string item in strUserID)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        UserIDList.Add(new Guid(item));
                    }
                }
                query = query.Where(t => UserIDList.Contains(t.CreatedByUserID));
            }

            totalRecord = query.Count();
            IList<WfActivityInstanceTasksEx> list = query.OrderByDescending(t => t.CreatedDateTime).Skip(skip).Take(take).ToList();
            return list;
        }
        /**
         * 
         * 
        */
        public IList<WfActivityInstanceTasksEx> GetTaskOfMineBusiness(Guid userID, int skip, int take, string dtStart, string dtEnd,
         string kewyword, string UserIDs, string DeparmentID, String ProcessGuid,
         out int totalRecord)
        {
            var efemployeeInfoProvider = FB.Providers.AspNetEmployeeInfoProviderManager.Default as FB.Providers.EFEmployeeInfoProvider;
            FB.Providers.EmployeeInfo.EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            var queryTasks = GetBusinessActivityInstanceTasks();

            var query = from item in queryTasks
                        where item.CreatedByUserID == userID && item.ProcessState == 2
                        && (item.TaskState == 1 || item.TaskState == 2)
                        && item.ActivityType == 4 && (item.ActivityState == 1 || item.ActivityState == 2) && item.ProcessGUID == new Guid("0e37f0c1-737b-4653-93dd-d01a3fbc28f7") &&
                        (item.ActivityName.Contains("法务确认") || item.ActivityName.Contains("总经理") || item.ActivityName.Contains("总裁办"))
                        select item;
            var query1 = from item in queryTasks
                         group item by item.AppInstanceID into gitem
                         select new { gitem.Key, TaskID = gitem.Max(mm => mm.TaskID) };
            queryTasks = from item in queryTasks
                         from kk in query1
                         where item.AppInstanceID == kk.Key && item.TaskID == kk.TaskID
                         select item;

            var logQuery = from item in queryTasks
                           from log in DBHelper.FormCirculatedDocumentLog
                           where item.AppInstanceID == log.AppInstanceID && log.Status == 0 && log.UserID == userID
                           select new WfActivityInstanceTasksEx()
                           {
                               ActivityGUID = item.ActivityGUID,
                               ActivityInstanceID = item.ActivityInstanceID,
                               ActivityName = item.ActivityName,
                               ActivityState = item.ActivityState,
                               ActivityType = item.ActivityType,
                               AppInstanceID = item.AppInstanceID,
                               AppName = item.AppName,
                               AssignedToUserID = item.AssignedToUserID,
                               AssignedToUserName = item.AssignedToUserName,
                               CreatedByUserID = item.CreatedByUserID,
                               CreatedByUserName = item.CreatedByUserName,
                               CreatedDateTime = item.CreatedDateTime,
                               EndedByUserID = item.EndedByUserID,
                               EndedByUserName = item.EndedByUserName,
                               EndedDateTime = item.EndedDateTime,
                               IsActivityCompleted = item.IsActivityCompleted,
                               ProcessGUID = item.ProcessGUID,
                               ProcessInstanceID = item.ProcessInstanceID,
                               ProcessState = item.ProcessState,
                               TaskID = item.TaskID,
                               TaskState = item.TaskState,
                               TaskType = item.TaskType,
                               RecordStatusInvalid = item.RecordStatusInvalid,
                               ReadyTaskType = log.CheckType == 1 ? 2 : 3,
                               SendUserID = log.CreateUserID,
                               State = item.State
                           };
            query = query.Concat(logQuery);
            if (!string.IsNullOrEmpty(dtStart) && !string.IsNullOrEmpty(dtEnd))
            {
                DateTime dtStartTime = DateTime.Parse(dtStart);
                DateTime dtEndTime = DateTime.Parse(dtEnd);
                query = query.Where(t => t.CreatedDateTime >= dtStartTime && t.CreatedDateTime <= dtEndTime);
            }
            if (!string.IsNullOrEmpty(kewyword))
            {
                long appInstanceId = 0;
                long.TryParse(kewyword, out appInstanceId);
                if (appInstanceId > 0)
                {
                    query = query.Where(t => t.AppInstanceID == appInstanceId);
                }
                else
                {
                    query = query.Where(t => t.AppName.IndexOf(kewyword) > -1);
                }
            }
            if (!string.IsNullOrEmpty(ProcessGuid))
            {
                query = query.Where(t => t.ProcessGUID == new Guid(ProcessGuid));
            }
            if (!string.IsNullOrEmpty(DeparmentID))
            {
                IList<vw_Employees> employee = Regularrespository.GetEmployeeByDeparment(DeparmentID);
                foreach (var i in employee)
                {
                    UserIDs = UserIDs + ";" + i.UserID.ToString();
                }
            }
            if (!string.IsNullOrEmpty(UserIDs))
            {
                List<Guid?> UserIDList = new List<Guid?>();
                string[] strUserID = UserIDs.Split(";".ToArray());
                foreach (string item in strUserID)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        UserIDList.Add(new Guid(item));
                    }
                }
                query = query.Where(t => UserIDList.Contains(t.CreatedByUserID));
            }
            query = query.Where(t => t.CreatedByUserID == userID);
            totalRecord = query.Count();
            IList<WfActivityInstanceTasksEx> list = query.OrderByDescending(t => t.CreatedDateTime).Skip(skip).Take(take).ToList();
            return list;
        
        }

        public static IQueryable<WfActivityInstanceTasksEx> GetBusinessActivityInstanceTasks()
        {
            var query = from item in DBHelper.WfActivityInstance
                        join task in DBHelper.WfTasks on item.ID equals task.ActivityInstanceID
                        join processInstance in DBHelper.WfProcessInstance on item.ProcessInstanceID equals processInstance.ID
                        select new WfActivityInstanceTasksEx()
                        {
                            ActivityGUID = item.ActivityGUID,
                            ActivityInstanceID = task.ActivityInstanceID,
                            ActivityName = task.ActivityName,
                            ActivityState = item.State,
                            ActivityType = item.ActivityType,
                            AppInstanceID = item.AppInstanceID,
                            AppName = item.AppName,
                            AssignedToUserID = task.AssignedToUserID,
                            AssignedToUserName = task.AssignedToUserName,
                            CreatedByUserID = processInstance.CreatedByUserID,
                            CreatedByUserName = item.CreatedByUserName,
                            CreatedDateTime = task.CreatedDateTime,
                            EndedByUserID = task.EndedByUserID,
                            EndedByUserName = task.EndedByUserName,
                            EndedDateTime = task.EndedDateTime,
                            IsActivityCompleted = item.IsActivityCompleted,
                            ProcessGUID = item.ProcessGUID,
                            ProcessInstanceID = item.ProcessInstanceID,
                            ProcessState = processInstance.ProcessState,
                            TaskID = task.ID,
                            TaskState = task.TaskState,
                            TaskType = task.TaskType,
                            RecordStatusInvalid = task.RecordStatusInvalid,
                            ReadyTaskType = 1,
                            SendUserID = Guid.NewGuid(),

                            // 测试为了判断是否是撤回而建立
                            State = item.State
                        };
            return query;
        }
        #endregion
    }
}
